package com.i2works.smartluolong.manage.service.common;


import com.i2works.smartluolong.manage.entity.admin.AdminUserDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

/**
 * 密码生成策略
 *
 * @author koal koal@vip.qq.com
 * @date 2016年1月3日 下午2:39:26
 * 通过RandomNumberGenerator生成随机数，设置为salt，
 * 然后userName+salt当做掩码生成密码
 */
@Component
public class AdminPasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    //    @Value("${password.algorithmName}")
    private String algorithmName = "md5";
    //    @Value("${password.hashIterations}")
    private int hashIterations = 2;

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    /**
     * 加密过程
     *
     * @param password 密码
     * @param salt     盐
     * @return 加密后的密码
     */
    public String encryptPassword(String password, String salt) {
        if (StringUtils.isBlank(salt)) {
            salt = randomNumberGenerator.nextBytes().toHex();
        }
        return new SimpleHash(algorithmName, password, ByteSource.Util.bytes(salt), hashIterations).toHex();
    }


    /**
     * 管理员
     */
    public void encryptPassword(AdminUserDO admin) {
        admin.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(
                algorithmName,
                admin.getPassword(),
                ByteSource.Util.bytes(admin.getCredentialsSalt()),
                hashIterations).toHex();
        admin.setPassword(newPassword);
    }

}
